/**
 * 定义一个require模块，并依赖app模块
 */
define(["app", "popup/popup-jpress", "util/current-tab"], function(app, jpress, currentTab) {

    /*
    platform = {
        "valid":true,
        "reason":"",
        "nickname":"N小聪",
        "platformName":"jianshu",
        "userId":"20451298",
        "platformDisplayName":"简书"
    }
     */
    var platform;


    var init = function(item, plat){
        platform = plat;
        item.bind("click", showMenu);
        // 无效时检测是否在简书界面中
        platform.valid || detect();
    }

    var showMenu = function(){
        if(!platform || !platform.valid){
            $.actions({
                title : platform.reason,
                actions: [{
                    text: "打开" + platform.platformDisplayName + "设置",
                    onClick: function(){
                        $.alert("请在新打开的窗口<br/>使用手机验证码<br/>登陆头条号后重新打开插件", "", goLoginPage);
                    }
                }]
            });
        } else {
            $.toptip("配置正常", 1000, "success")
        }
    }

    var detect = function(){
        if(currentTab.domain !== "mp.toutiao.com"){
            return;
        }
        // 调用api查询当前页面对应的cookie
        chrome.cookies.getAll({
            "name" : "sessionid",
            "domain" : ".toutiao.com"
        }, function(cookies){
            // console.log("简书cookie-init：" + JSON.stringify(cookies));
            var sessionid = cookies && cookies[0] ? cookies[0].value : false;
            if(!sessionid){
                return;
            }
            console.log("popup-toutiao.js [detect] - 头条cookie[sessionid]：" + sessionid);
            $.when(
                // 查询用户
                app.sendGet(currentTab.tabId, currentTab.createUrl("/user_login_status_api/"), cookies),
                // 查询文集
                // app.sendGet(currentTab.tabId, currentTab.createUrl("/author/notebooks"), cookies),
                "a"
            ).done(function(userResp){
                //{ "message": "success", "now": 1578466659, "data": "", "reason": { "media": { "avatar_info_ok": true, "is_media": true, "verified_info_ok": true, "media_info_ok": true, "media_status_ok": true, "media_info": { "media_id": 1653440036364299, "avatar_url": "http://p1.pstatp.com/large/pgc-image/90d0adad8d884834b6de0611697918bc", "user_id": 927643333574455, "name": "N小聪" }, "can_renew_account": false }, "user": { "is_virtual_mobile": false, "user_status_ok": true, "mobile_bind_ok": true, "is_login": true } } }
                console.log("头条用户：" + JSON.stringify(userResp))
                if(!userResp || !userResp.reason || !userResp.reason.media || !userResp.reason.media.media_info){
                    $.alert("查询头条号媒体信息失败", "数据异常")
                    return;
                }
                dologin({
                    mediaId : userResp.reason.media.media_info.media_id,
                    sessionid : sessionid,
                    nickname : userResp.reason.media.media_info.name
                })
            }).fail(function(e){
                $.alert(JSON.stringify(e), "系统异常");
            })
        });
    }

    var goLoginPage = function(){
        // https://mp.toutiao.com/auth/page/login/?hideThird=true
        chrome.tabs.create({'url': 'https://mp.toutiao.com/auth/page/login/?hideThird=true'});
    }

    /**
     * 用当前页面配置信息登陆
     * @param conf = {
            mediaId : "xxxxx",
            sessionid : "xxxxx",
            nickname : "xxxx"
        }
     */
    var dologin = function(conf){
        $.confirm("是否保存名为<br/>" + conf.nickname + "（" + conf.mediaId + "）<br/>的头条号", "", function() {
            // 整理文集信息并弹出选择菜单
            $.actions({
                title: "选择发布方式",
                actions: [{
                    text: "直接发布",
                    onClick: function(){doSaveConfig(conf.mediaId, conf.sessionid, false);}
                },{
                    text: "手动发布（只保存草稿）",
                    onClick: function(){doSaveConfig(conf.mediaId, conf.sessionid, true);}
                }]
            })
        })
    }

    // 保存配置到插件后台
    var doSaveConfig = function(mediaId, sessionid, draftOnly){
        var config = {
            enable : true,
            mediaId : mediaId,
            draftOnly : draftOnly && true,
            cookie : "sessionid=" + sessionid + ";"
        }
        console.log("popup-toutiao.js [doSaveConfig] - " + JSON.stringify(config));
        // 保存内容
        jpress.doSavePlatform("toutiao", config)
    }


    /**
     * 向外暴露方法
     */
    return {
        init : init
    }
})